package com.ts.jdbc;

import com.ts.constant.SysConst;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

/**
 * Created by home on 2017/3/11.
 * 涉及到数据库的事务管理，需要在数据库事务开启切换数据库，
 否则数据库的切换只能在下次数据库操作时才生效
 */

public class DataSourceAspect implements MethodBeforeAdvice,AfterReturningAdvice {

    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        DataSourceHolder.clearDataSourceType();
    }

    public void before(Method method, Object[] objects, Object target) throws Throwable {
        if (method.isAnnotationPresent(DataSource.class))
        {
            DataSource datasource = method.getAnnotation(DataSource.class);
            DataSourceHolder.setDataSource(datasource.value());
        }
        else
        {
            //默认数据源
                DataSourceHolder.setDataSource(SysConst.DefaultSource);
        }
    }
}
